import React, { useReducer, useState, useEffect, Fragment } from 'react';
import { Card, notification, Modal, Button } from 'antd';
import ScoresForm from './components/ScoresForm';
import TableList from './components/TableList';
import AddScoresModal from './components/AddScoresModal';
import DownloadModal from './components/DownloadModal';

import EditScoresModal from './components/EditScoresModal';
import { SIZE, PAGE, ALL } from '@/utils/constant';
import { scoresList, gradesList, classList, delScores } from '@/services/api';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
    pageSizeOptions: ['10', '30', '50', '70', '90'],
  },
  searchValue: {},
};

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

const List = () => {
  const [modal, setModal] = useState(false);
  const [isAddModal, setIsAddModal] = useState(false);
  const [isDownloadModal, setIsDownloadModal] = useState(false);
  const [gradesData, setGradesData] = useState([]);
  const [clasesData, setClasesData] = useState([]);
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    gradesList({ page: PAGE, size: ALL }).then((res: any) => {
      if (res.status === 'success') {
        setGradesData(res.data.data);
      }
    });
    classList({ page: PAGE, size: ALL }).then((res: any) => {
      if (res.status === 'success') {
        setClasesData(res.data.data);
      }
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    scoresList({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    scoresList({ ...searchValue, page: changePagination.current, size: changePagination.pageSize })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '姓名',
      key: 'student',
      dataIndex: 'student',
      render: (text: any) => <span>{text && text.name}</span>,
    },
    {
      title: '学期',
      key: 'semester',
      dataIndex: 'semester',
    },
    {
      title: '语文',
      key: 'chinese',
      dataIndex: 'chinese',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '数学',
      key: 'math',
      dataIndex: 'math',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '英语',
      key: 'english',
      dataIndex: 'english',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '政治',
      key: 'politics',
      dataIndex: 'politics',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '历史',
      key: 'history',
      dataIndex: 'history',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '地理',
      key: 'geographic',
      dataIndex: 'geographic',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '生物',
      key: 'biological',
      dataIndex: 'biological',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '物理',
      key: 'physical',
      dataIndex: 'physical',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '化学',
      key: 'chemical',
      dataIndex: 'chemical',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '体育',
      key: 'sport',
      dataIndex: 'sport',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '音乐',
      key: 'music',
      dataIndex: 'music',
      sorter: (a: any, b: any) => a.chinese - b.chinese,
    },
    {
      title: '修改时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
    },
    {
      title: '修改成绩',
      key: 'operation',
      dataIndex: 'id',
      render: (text: any, record: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <a
            onClick={e => {
              e.preventDefault();
              setModal(true);
              sessionStorage.setItem('scoresData', JSON.stringify(record));
            }}
          >
            修改
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  delScores(text).then((resp: any) => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      scoresList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            删除
          </a>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <Card title="成绩列表">
        <ScoresForm dispatch={dispatch} gradesData={gradesData} clasesData={clasesData} />
      </Card>
      <Card className="pageCard">
        <Button
          type="primary"
          icon="upload"
          onClick={() => {
            setIsAddModal(true);
          }}
          style={{ marginBottom: 24 }}
        >
          导入成绩
        </Button>
        <Button
          type="primary"
          icon="download"
          onClick={() => {
            setIsDownloadModal(true);
          }}
          style={{ marginBottom: 24, marginLeft: 16 }}
        >
          下载模板
        </Button>
        <TableList
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
      {modal && (
        <EditScoresModal
          dispatch={dispatch}
          onClose={() => {
            setModal(false);
          }}
        />
      )}
      {isAddModal && (
        <AddScoresModal
          dispatch={dispatch}
          onClose={() => {
            setIsAddModal(false);
          }}
        />
      )}
      {isDownloadModal && (
        <DownloadModal
          onClose={() => {
            setIsDownloadModal(false);
          }}
          clasesData={clasesData}
        />
      )}
    </Fragment>
  );
};

export default List;
